const fs = require('fs');

let renderFun = dir => async (ctx, next) => {
	console.log('dir', dir)
	let view = dir
	if (view.indexOf(':') >= 0) {
		view = view.split(':')
		view = view[0] + ctx.params[view[1]]
	}
	let controller = '../controllers/' + view + '.js'  
	if (fs.existsSync(__dirname.substr(0, __dirname.length - 7) + controller.substr(2).replace(/\//g, '\\'))) {
		let obj = await require('../controllers/' + view + '.js')()
		console.log('controller', view, 'result:', obj)
		await ctx.render(view, obj)
	} else {
		console.log('no controller', view)
		await ctx.render(view) 
	}
}

let postFun = dir => async (ctx, next) => {
	let view = dir
	console.info('post method:', ctx.params.method, 'post data:', ctx.request.body)
	let obj = await require('../controllers/_module/' + view + '.js')(ctx.params.method, ctx.request.body)
	console.log('post response:', obj)
    ctx.response.type = 'application/json';
    ctx.response.body = obj
}

module.exports = {
	basepath: '/',
	routeArr:[
		{
			method: 'get',
			path: '/',
			func: renderFun('index/index')
        },
        {
            method: 'get',
            path: '/tg',
			func: renderFun('tg/tg')
        },
        {
            method: 'get',
            path: '/proList',
			func: renderFun('proList/proList')
        },
        {
            method: 'get',
            path: '/aboutUs',
			func: renderFun('aboutUs/aboutUs')
		},	

        {
            method: 'get',
            path: '/form/:type',
			func: renderFun('form/:type')
		},
        {
            method: 'get',
            path: '/usercenter/:type',
			func: renderFun('usercenter/:type')
		},

		{
			method: 'post',
			path: '/login/:method',
			func: postFun('login')
		}
	]
}